import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext
import random
from collections import Counter
from alg import Solution

class RabbitCounterApp:
    def __init__(self, root):
        self.root = root
        self.root.title("兔子数量计算器")
        self.root.geometry("700x500")
        self.root.minsize(600, 400)
        self.root.configure(bg="#f0f0f0")
        
        # 设置字体，确保中文显示正常
        self.default_font = ('SimHei', 10)
        self.title_font = ('SimHei', 16, 'bold')
        self.header_font = ('SimHei', 12, 'bold')
        
        self.create_widgets()
        
    def create_widgets(self):
        # 创建主框架
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 标题
        title_label = ttk.Label(main_frame, text="兔子数量计算器", font=self.title_font)
        title_label.grid(row=0, column=0, columnspan=2, pady=10)
        
        # 输入区域
        input_frame = ttk.LabelFrame(main_frame, text="输入数据", padding="10")
        input_frame.grid(row=1, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), padx=10, pady=10)
        
        ttk.Label(input_frame, text="兔子的回答 (用英文逗号分隔):", font=self.default_font).grid(row=0, column=0, sticky=tk.W, pady=5)
        
        self.answers_entry = scrolledtext.ScrolledText(input_frame, width=30, height=5, font=self.default_font)
        self.answers_entry.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=5)
        
        button_frame = ttk.Frame(input_frame)
        button_frame.grid(row=2, column=0, sticky=(tk.W, tk.E), pady=10)
        
        ttk.Button(button_frame, text="生成随机数据", command=self.generate_random_data).pack(side=tk.LEFT, padx=5)
        ttk.Button(button_frame, text="计算结果", command=self.calculate_result).pack(side=tk.LEFT, padx=5)
        
        # 结果区域
        result_frame = ttk.LabelFrame(main_frame, text="计算结果", padding="10")
        result_frame.grid(row=1, column=1, sticky=(tk.W, tk.E, tk.N, tk.S), padx=10, pady=10)
        
        ttk.Label(result_frame, text="输入数据:", font=self.header_font).grid(row=0, column=0, sticky=tk.W, pady=5)
        self.input_display = tk.Text(result_frame, width=30, height=3, font=self.default_font, state="disabled")
        self.input_display.grid(row=1, column=0, sticky=(tk.W, tk.E), pady=5)
        
        ttk.Label(result_frame, text="兔子最少数量:", font=self.header_font).grid(row=2, column=0, sticky=tk.W, pady=5)
        self.total_display = ttk.Label(result_frame, text="", font=('SimHei', 14, 'bold'), foreground="#4F46E5")
        self.total_display.grid(row=3, column=0, sticky=tk.W, pady=5)
        
        ttk.Label(result_frame, text="详细分析:", font=self.header_font).grid(row=4, column=0, sticky=tk.W, pady=5)
        self.analysis_display = scrolledtext.ScrolledText(result_frame, width=30, height=10, font=self.default_font, state="disabled")
        self.analysis_display.grid(row=5, column=0, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
        
        # 设置权重，使界面可伸缩
        main_frame.columnconfigure(0, weight=1)
        main_frame.columnconfigure(1, weight=1)
        main_frame.rowconfigure(1, weight=1)
        
        result_frame.rowconfigure(5, weight=1)
    
    def calculate_result(self):
        """计算兔子的最少数量"""
        input_text = self.answers_entry.get("1.0", tk.END).strip()
        
        if not input_text:
            messagebox.showwarning("警告", "请输入兔子的回答数据")
            return
        
        try:
            # 解析输入数据
            answers = [int(num.strip()) for num in input_text.split(',') if num.strip()]
            
            if not answers:
                messagebox.showwarning("警告", "未找到有效的数字数据")
                return
            
            solution = Solution()
            total = solution.numRabbits(answers)
            analysis = self.generate_analysis(answers)
            
            # 更新显示
            self.update_display(answers, total, analysis)
            
        except ValueError as e:
            messagebox.showerror("错误", f"输入格式错误: {e}")
        except Exception as e:
            messagebox.showerror("错误", f"处理数据时出错: {e}")
    
    def generate_analysis(self, answers):
        """生成详细分析"""
        if not answers:
            return []
        
        count_map = Counter(answers)
        
        analysis = []
        
        for v, k in count_map.items():
            group_size = v + 1
            groups = (k + group_size - 1) // group_size  # 向上取整
            rabbits = groups * group_size
            
            analysis.append({
                'answer': v,
                'count': k,
                'group_size': group_size,
                'groups': groups,
                'rabbits': rabbits
            })
        
        return analysis
    
    def update_display(self, answers, total, analysis):
        """更新显示结果"""
        self.input_display.config(state="normal")
        self.input_display.delete("1.0", tk.END)
        self.input_display.insert(tk.END, ", ".join(map(str, answers)))
        self.input_display.config(state="disabled")
        
        self.total_display.config(text=str(total))
        
        self.analysis_display.config(state="normal")
        self.analysis_display.delete("1.0", tk.END)
        
        for item in analysis:
            self.analysis_display.insert(tk.END, f"回答值为 {item['answer']} 的兔子:\n")
            self.analysis_display.insert(tk.END, f"  出现次数: {item['count']}\n")
            self.analysis_display.insert(tk.END, f"  每组大小: {item['group_size']}\n")
            self.analysis_display.insert(tk.END, f"  需要组数: {item['groups']}\n")
            self.analysis_display.insert(tk.END, f"  最少数量: {item['rabbits']}\n\n")
        
        self.analysis_display.config(state="disabled")
    
    def generate_random_data(self):
        """生成随机测试数据"""
        count = random.randint(1, 10)
        answers = [random.randint(0, 10) for _ in range(count)]
        
        self.answers_entry.delete("1.0", tk.END)
        self.answers_entry.insert(tk.END, ", ".join(map(str, answers)))

if __name__ == "__main__":
    
    root = tk.Tk()
    app = RabbitCounterApp(root)
    root.mainloop()    
